<template>
  <div>
    <div class="iptWp" v-if="type == 'input'">
      <input type="text" v-maxLength="maxlength" v-model="ipt" />
      <span class="span">0/{{ maxlength }}</span>
    </div>
    <div class="iptWp" v-else-if="type == 'textarea'">
      <textarea
        v-maxLength="maxlength"
        v-model="ipt"
        cols="30"
        rows="10"
      ></textarea>
      <span class="spantextarea">0/{{ maxlength }}</span>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    type: {
      default: "input",
      type: String,
    },
    maxlength: {
      default: 10,
      type: [String, Number],
    },
  },
  data() {
    return {
      ipt: "",
    };
  },
  directives: {
    maxLength: {
      inserted(el, binding) {
        el.setAttribute("maxlength", binding.value);
      },
      update(el, binding) {
        let iptLen = el.value.length;
        let span = el.nextElementSibling;
        span.innerHTML = iptLen + "/" + binding.value;
        if (iptLen == binding.value) {
          el.style.color = "coral";
        } else {
          el.style.color = "";
        }
      },
    },
  },
};
</script>

<style scoped>
.iptWp {
  position: relative;
  display: inline-block;
}

.span {
  position: absolute;
  top: 5px;
  right: 3px;
  font-size: 10px;
  color: #999;
}

.spantextarea {
  position: absolute;
  bottom: 8px;
  right: 5px;
  font-size: 10px;
  color: #999;
}
</style>
